{% extends 'backend/home-list.html' %}
{% load static %}
{% block Link %}
    <link rel="stylesheet" href="{% static 'smarty/css/theme.docs.css' %}">
    <!-- One of the following themes -->
    <link rel="stylesheet" href="{% static 'pickr/themes/classic.min.css' %}"/>
    <!-- 'classic' theme -->
    <link rel="stylesheet" href="{% static 'pickr/themes/monolith.min.css' %}"/>
    <!-- 'monolith' theme -->
    <link rel="stylesheet" href="{% static 'pickr/themes/nano.min.css' %}"/>
    <!-- 'nano' theme -->

{% endblock %}

{% block Primary %}
    <div class="row g-3 mb-3">
        <!-- 收入 -->
        {% for pay_type, categories in pay_categories.items %}
            <div class="col-12 col-xl-4">

                <div class="portlet">

                    <div class="portlet-header">
                        <div class="float-end">
                            <button type="button" onclick="addPayCategory({{ pay_type }})"
                                    class="btn rounded-pill btn-sm btn-primary transition-hover-top mb-1"
                                    data-bs-toggle="modal" data-bs-target="#modalPayCategory">添加
                            </button>
                        </div>
                        <span class="d-block text-muted text-truncate fw-medium">
                    {% if pay_type == 'spending' %}
                        支出
                    {% elif pay_type == 'income' %}
                        收入
                    {% else %}
                        转账
                    {% endif %}
                  </span>
                    </div>

                    <div class="portlet-body max-h-500 tab-content">

                        <!-- tab 1 -->
                        <div id="pay-category-{{ pay_type }}" class="timer-countdown timer-countdown-inline small">
                            {% for category in categories %}
                                <span data-id="{{ category.id }}"
                                      data-color="{{ category.color }}"
                                      data-name="{{ category.name }}"
                                      data-pay_type="{{ category.pay_type }}"
                                      data-icon="{{ category.icon }}"
                                      onclick="editPayCategory(this)"
                                      class="bg-white shadow rounded p-2 m-1 text-center d-inline-block">
                                    <span class=" iconfont icon-{{ category.icon }} fs-3"
                                          style="color: {{ category.color }};"></span>
                                    <div class="smaller text-muted">{{ category.name }}</div>
                                </span>
                            {% endfor %}
                        </div>
                    </div>

                </div>

            </div>
        {% endfor %}
        <!-- /收入 -->


    </div>
    <div class="row g-3 mb-3">
        <div class="section mb-4">
            <div class="h6 card-header border-bottom-0 fw-bold">添加分类</div>
            <div class="card-body">
                <form id="paycategory-form">
                    <div class="row g-3">
                        <div class="col-sm-1">
                            <span id="categoryIcon"
                                  class="icon iconfont icon-{{ ali_icons.0.font_class }} fs-1"></span>
                            <input hidden name="icon" value="{{ ali_icons.0.font_class }}" id="paycategory-icon"
                                   class="form-control mb-3" placeholder="图标">
                        </div>
                        <div class="col-sm-1">
                            {#  颜色选择器#}
                            <input hidden name="color" value="#249af5" id="paycategory-color" placeholder="颜色">
                            <input placeholder="颜色选择器" class="form-control mb-3 color-picker">
                        </div>
                        <div class="col-sm-3">
                            <div class="form-floating">
                                <select class="form-select shadow-none" id="paycategory-pay_type" name="pay_type"
                                        aria-label="State">
                                    <option value="spending">支出</option>
                                    <option value="income">收入</option>
                                    <option value="transfer">转账</option>
                                </select>
                                <label for="shipping__state">类型</label>
                            </div>
                        </div>
                        <div class="col-sm-3">
                            <div class="form-floating">
                                <input type="text" class="form-control shadow-none" name="name" id="paycategory-name"
                                       data-rule="required:true|maxlength:5" placeholder="名称">
                                <label for="floatingInput">名称<span class="text-danger">*</span></label>
                                <div class="invalid-feedback" id="paycategory-name-err">
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-3">
                            <div class="form-floating">
                                <button type="button" onclick="payCategorySave()" class="btn btn-primary">
                                    <svg width="18px" height="18px" xmlns="http://www.w3.org/2000/svg"
                                         viewBox="0 0 24 24"
                                         fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                         stroke-linejoin="round">
                                        <polyline points="20 6 9 17 4 12"></polyline>
                                    </svg>
                                    <span>保存</span>
                                </button>
                            </div>

                        </div>

                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="row g-3 mb-3">
        <div class="doc-content">

            <div id="container-icon">

                <!-- Inline Search -->
                <form class="subnav-search d-flex flex-nowrap ms-auto mt-0 sticky-top">
                    <input class="form-control form-control-lg search mb-0 border-light shadow-lg mt-1" id="search"
                           placeholder="Icon search..." autocomplete="off">
                </form>
                <ul class="list doc-icon-preview" data-vendor-path="" data-vendor-available="svg"
                    data-vendor-webfont-prefix="" id="iconsUl">
                    {% for icon in ali_icons %}
                        <li onclick="selectIcon('{{ icon.font_class }}')" data-icon="{{ icon.font_class }}"
                            style="height: 80px;width: 100px;">
                            <span class="icon iconfont icon-{{ icon.font_class }} fs-3"></span>
                            <p>{{ icon.name }}</p>
                        </li>
                    {% endfor %}
                </ul>
            </div>
        </div>
    </div>

{% endblock %}

{% block javaScripts %}
    {{ block.super }}
    <!-- Modern or es5 bundle -->
    <script src="{% static 'pickr/pickr.min.js' %}"></script>
    <script src="{% static 'pickr/pickr.es5.min.js' %}"></script>
    <script>

        {#颜色分类#}
        // Simple example, see optional options for more configuration.
        const pickr = Pickr.create({
            el: '.color-picker',
            theme: 'classic', // or 'monolith', or 'nano'
            default: '#249af5',
            swatches: [
                'rgba(244, 67, 54, 1)',
                'rgba(233, 30, 99, 0.95)',
                'rgba(156, 39, 176, 0.9)',
                'rgba(103, 58, 183, 0.85)',
                'rgba(63, 81, 181, 0.8)',
                'rgba(33, 150, 243, 0.75)',
                'rgba(3, 169, 244, 0.7)',
                'rgba(0, 188, 212, 0.7)',
                'rgba(0, 150, 136, 0.75)',
                'rgba(76, 175, 80, 0.8)',
                'rgba(139, 195, 74, 0.85)',
                'rgba(205, 220, 57, 0.9)',
                'rgba(255, 235, 59, 0.95)',
                'rgba(255, 193, 7, 1)'
            ],

            components: {

                // Main components
                preview: true,
                opacity: true,
                hue: true,

                // Input / output Options
                interaction: {}
            }
        });
        pickr.on('change', (color, source, instance) => {
            const hexa_color = pickr.getColor().toHEXA().toString()
            $("#categoryIcon").css("color", hexa_color);
            $("#iconsUl").css("color", hexa_color);
            $("#paycategory-color").val(hexa_color);
            pickr.applyColor(true);
        })

        const el_0 = document.getElementById('pay-category-income');
        const el_1 = document.getElementById('pay-category-spending');
        const el_2 = document.getElementById('pay-category-other');
        console.log(el_0)
        var ops = {
            animation: 1000,

            //拖动结束
            onEnd: function (evt) {
                {#console.log(evt);#}
                //获取拖动后的排序
                {#console.log(evt.oldDraggableIndex, evt.newDraggableIndex, evt.item.dataset.id)#}
                {#console.log("你正在拖动：" + evt.dragged.dataset.id + ",替换了：" + evt.related.dataset.id);#}
                {#console.log("B组排序结果：" + JSON.stringify(sortable.toArray()))#}
                //}

                $.ajax({
                    url: "{% url 'api-expense:expense-category-move' 0 %}".replace(/0/, evt.item.dataset.id),
                    type: "POST",
                    data: JSON.stringify({'sort': evt.newDraggableIndex}),
                    contentType: 'application/json;charset=UTF-8', //contentType很重要
                    dataType: 'json',
                    success: function (res) {
                        {#console.log(res)#}
                    },
                    error: function (jqXHR) {
                        ajax_error(jqXHR)
                    }
                })

            },
        };
        //初始化
        var sortable0 = Sortable.create(el_0, ops);
        var sortable1 = Sortable.create(el_1, ops);
        var sortable2 = Sortable.create(el_2, ops);

        // 选择图标
        function selectIcon(icon) {

            var patt1 = new RegExp('^icon-.*$');
            var icon_span = document.getElementById('categoryIcon')
            icon_span.classList.forEach(function (cl) {
                if (patt1.test(cl)) {
                    icon_span.classList.remove(cl)
                    icon_span.classList.add('icon-' + icon) // 替换选择的图标
                    $("#paycategory-icon").val(icon);
                }
            })
        }

        var EDIT_PAY_CATEGORY_ID = null

        function payCategorySave() {
            const cur_form_inputs = $('[data-rule][id^=paycategory-]')
            cur_form_inputs.trigger('blur')
            let flag = Input.input_validate(cur_form_inputs)
            if (flag) {
                var forms = document.getElementById('paycategory-form')
                var formData = new FormData(forms);
                for (var [a, b] of formData.entries()) {
                    console.log(a, b);
                }
                let url = ''
                let method = ''
                if (EDIT_PAY_CATEGORY_ID == null) {
                    url = "{% url 'api-expense:expense-category-list' %}"
                    method = 'POST'
                } else {
                    url = "{% url 'api-expense:expense-category-detail' 0 %}".replace(/0/, EDIT_PAY_CATEGORY_ID)
                    method = 'PUT'
                }

                $.ajax({
                    url: url,
                    type: method,
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        $.SOW.core.toast.show('success', '', '操作成功', 'top-center', 10000, true);
                        $('#paycategory-name').val(''); // name input 设置空
                        {# 添加到指定的列表中#}
                        location.reload() // 刷新当前页面
                    },
                    error: function (jqXHR) {
                        ajax_error(jqXHR, 'paycategory')
                    }
                })
            }
        }

        function editPayCategory(el) {
            console.log(el.dataset)
            document.getElementById('paycategory-pay_type').value = el.dataset.pay_type
            document.getElementById('paycategory-name').value = el.dataset.name
            document.getElementById('paycategory-color').value = el.dataset.color
            document.getElementById('paycategory-icon').value = el.dataset.icon
            pickr.setColor(el.dataset.color)
            selectIcon(el.dataset.icon)
            EDIT_PAY_CATEGORY_ID = el.dataset.id
        }
    </script>

{% endblock %}

